﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BrightIdeasSoftware;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraWaitForm;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.BusinessLogic.FileTransferService;
using FileManager_Client.PresentationLayer.Properties;
using FileManager_Client.Utility;
using Paway.Windows.Forms;
using FileManager_Client.PresentationLayer.Common;

namespace FileManager_Client.PresentationLayer.NewUi
{
    public partial class FileManager_Form : BaseForm
    {
        #region Constructor
        private CompanyResultCollection companyCollection;
        private FolderResultCollection folderCollection;
        private FolderRoleResultCollection folderRoleCollection;
        private UserLoginResult userSession;
        private LoadingWaitForm loadingWaitForm;
        private FileService fileService;
        private static object _lockObj = new object();
        private TreeNode selectNode;
        private DepartmentSizeResultCollection departmentSizeResultCollection;
        private static double CurrentDepartmentSize;
        private static double CurrentDepartmentUseSize;
        private static Dictionary<string, object> LockFiles = new Dictionary<string, object>(); 
        public FileManager_Form()
        {
            InitializeComponent();
            InitializeForm();
        }

        #endregion

        #region Initialize Form
        private void InitializeForm()
        {
            var toolBarLocationX = (Width - ToolBar_System.Width)/2;
            ToolBar_System.Location = new Point(toolBarLocationX, ToolBar_System.Location.Y);
            fileService = new FileService();
            CacheGlobal.Add(GlobalString.System_Config_String.Wcf_FileTransferServiceCacheKey,
                            new FileTransfer_ServiceClient());
            tvFileView.ExpandAll();
            InitializeTreeView();
            tvFileView.NodeMouseClick += tvFileView_NodeMouseClick;
            tvFileView.AfterSelect += tvFileView_AfterSelect;
            lvFileView.ColumnClick += lvFileView_ColumnClick;
            lvFileView.MouseDoubleClick += lvFileView_MouseDoubleClick;
            lvFileView.MouseClick += lvFileView_MouseClick;
            tvFileView.MouseDoubleClick += tvFileView_MouseDoubleClick;
            pgbRoom.Properties.PercentView = true;
            Shown += FileManager_Form_Shown;
            Shown += FileManager_Form_Shown_UploadingBreak;
            Shown += FileManager_Form_Shown_UploadLog;
            Shown += FileManager_Form_Shown_Downloading;
            Shown += FileManager_Form_Shown_DownloadLog;
            Shown += FileManager_Form_Shown_SystemConfig;
            #region Set Uploading Control
            Olv_Uploading.UseTranslucentHotItem = false;
            Olv_Uploading.UseHotItem = true;
            Olv_Uploading.UseExplorerTheme = false;
            var rbd = new RowBorderDecoration();
            rbd.BorderPen = new Pen(Color.SeaGreen, 2);
            rbd.FillBrush = null;
            rbd.CornerRounding = 4.0f;
            var hotItemStyle2 = new HotItemStyle {Decoration = rbd};
            Olv_Uploading.HotItemStyle = hotItemStyle2;
            Oc_UploadingFileName.ImageGetter = delegate(object row)
                                                   {
                                                       var uploadPro = row as UploadFileProgress;
                                                       if(null != uploadPro)
                                                           return ReturnImageKey(uploadPro.FileName);
                                                       return "1";
                                                   };
            #endregion
            #region Set UploadLog Control
            Olv_UploadLog.UseTranslucentHotItem = false;
            Olv_UploadLog.UseHotItem = true;
            Olv_UploadLog.UseExplorerTheme = false;
            Olv_UploadLog.HotItemStyle = hotItemStyle2;
            olv_FileName.ImageGetter = delegate(object row)
            {
                var uploadPro = row as UploadLogView;
                if (null != uploadPro)
                    return ReturnImageKey(uploadPro.FileName);
                return "1";
            };
            #endregion
            #region Set Downloading Control
            Olv_Downloading.UseTranslucentHotItem = false;
            Olv_Downloading.UseHotItem = true;
            Olv_Downloading.UseExplorerTheme = false;
            Olv_Downloading.HotItemStyle = hotItemStyle2;
            olv_DownlaodingFileName.ImageGetter = delegate(object row)
            {
                var uploadPro = row as DownloadingFileProgress;
                if (null != uploadPro)
                    return ReturnImageKey(uploadPro.FileName);
                return "1";
            };
            #endregion
            #region Set DownloadLog Control
            Olv_DownloadLog.UseTranslucentHotItem = false;
            Olv_DownloadLog.UseHotItem = true;
            Olv_DownloadLog.UseExplorerTheme = false;
            Olv_DownloadLog.HotItemStyle = hotItemStyle2;
            olv_DownloadLogFileName.ImageGetter = delegate(object row)
            {
                var uploadPro = row as DownloadLogView;
                if (null != uploadPro)
                    return ReturnImageKey(uploadPro.FileName);
                return "1";
            };
            #endregion
        }

        void FileManager_Form_Shown(object sender, EventArgs e)
        {
            ToolBar_System.SelectedIndex = (int)PageEnum.FileManagerPage;
        }

        private void InitializeTreeView()
        {
            companyCollection =
    CacheGlobal.GetCache(GlobalString.System_Config_String.CompanyCollectionCache) as
    CompanyResultCollection ??
    new CompanyResultCollection { CompanyResultsk__BackingField = new CompanyResult[0] };
            folderCollection =
                CacheGlobal.GetCache(GlobalString.System_Config_String.FolderCollectionCache) as
                FolderResultCollection ??
                new FolderResultCollection { FolderCollectionk__BackingField = new FolderResult[0] };
            folderRoleCollection =
                CacheGlobal.GetCache(GlobalString.System_Config_String.FolderRoleCollectionCache) as
                FolderRoleResultCollection ??
                new FolderRoleResultCollection { RoleResultsk__BackingField = new FolderRoleResult[0] };
            userSession =
                CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult
                ?? new UserLoginResult();
            departmentSizeResultCollection =
                CacheGlobal.GetCache(GlobalString.System_Config_String.DepartmentSizeCollectionCache) as DepartmentSizeResultCollection
                ?? new DepartmentSizeResultCollection();
            lvFileView.Items.Clear();
            tvFileView.Nodes.Clear();
            var rootNodeData =
                companyCollection.CompanyResultsk__BackingField.FirstOrDefault(x => x.Pidk__BackingField.Equals("0"));
            var rootNode = new TreeNode
            {
                Text = rootNodeData.ShortNamek__BackingField,
                ImageKey = GlobalString.System_Image_String.CompanyImageKey,
                Tag = rootNodeData,
                ContextMenuStrip = cms_NoRole,
                Name = rootNodeData.Idk__BackingField
            };
            rootNode.Expand();
            tvFileView.Nodes.Add(rootNode);
            var subNodeData =
                companyCollection.CompanyResultsk__BackingField.Where(
                    x => x.Pidk__BackingField.Equals(rootNodeData.Idk__BackingField)).ToList();
            foreach (var subNode in subNodeData.Select(companyResult => new TreeNode
            {
                Text = companyResult.ShortNamek__BackingField,
                ImageKey = GlobalString.System_Image_String.CompanyImageKey,
                Tag = companyResult,
                ContextMenuStrip = userSession.CompanyIdk__BackingField.Equals(companyResult.Idk__BackingField) ? cms_MyCompanyRootRole : cms_NoRole,
                Name = companyResult.Idk__BackingField
            }))
            {
                rootNode.Nodes.Add(subNode);
            }
            //FIND ROOT SUBFOLDER
            var rootFolder =
                folderCollection.FolderCollectionk__BackingField.Where(x => x.ParentIdk__BackingField.Equals("0")).
                    ToList();
            foreach (var folderInfo in rootFolder)
            {
                var contextMenuStrip = folderInfo.OwnerIdk__BackingField.Equals(userSession.CompanyIdk__BackingField)
                    || folderInfo.CreateIdk__BackingField.Equals(userSession.UserIdk__BackingField) ? cms_myComapnyFolderRole : cms_OtherComapnyFolderRole;
                var currentNode = tvFileView.Nodes.Find(folderInfo.OwnerIdk__BackingField, true);
                if (currentNode.Length <= 0) continue;
                var currentRoot = currentNode[0];
                var subFolderNode = new TreeNode
                {
                    Text = folderInfo.FileNamek__BackingField,
                    ImageKey = GlobalString.System_Image_String.FolderImageKey,
                    Tag = new NodeArgs { FolderResult = folderInfo },
                    ContextMenuStrip = contextMenuStrip,
                    Name = folderInfo.FileSidk__BackingField,
                    SelectedImageKey = GlobalString.System_Image_String.FolderOpenImageKey,
                };
                var currentSubFolderNodes = ReturnTreeNode(folderInfo.FileSidk__BackingField, contextMenuStrip);
                foreach (var currentSubFolderNode in currentSubFolderNodes)
                    subFolderNode.Nodes.Add(currentSubFolderNode);
                currentRoot.Nodes.Add(subFolderNode);
            }
            foreach (var folderRole in folderRoleCollection.RoleResultsk__BackingField)
            {
                var node = tvFileView.Nodes.Find(folderRole.FileIdk__BackingField, true);
                if (!node.Any()) continue;
                var objArgs = node[0].Tag as NodeArgs;
                if (null == objArgs) continue;
                objArgs.FolderRoleResult = folderRole;
                node[0].Tag = objArgs;
            }
            tvFileView.Update();
        }

        private IEnumerable<TreeNode> ReturnTreeNode(string parentId, ContextMenuStrip contextMenuStrip)
        {
            var result = new List<TreeNode>();
            var subFolders =
                folderCollection.FolderCollectionk__BackingField.Where(x => x.ParentIdk__BackingField.Equals(parentId)).
                    ToList();
            foreach (var folderResult in subFolders)
            {
                var subFolderNode = new TreeNode
                {
                    Text = folderResult.FileNamek__BackingField,
                    ImageKey = GlobalString.System_Image_String.FolderImageKey,
                    Tag = new NodeArgs { FolderResult = folderResult },
                    ContextMenuStrip = contextMenuStrip,
                    Name = folderResult.FileSidk__BackingField,
                    SelectedImageKey = GlobalString.System_Image_String.FolderOpenImageKey
                };
                var subsubNodes = ReturnTreeNode(folderResult.FileSidk__BackingField, contextMenuStrip);
                foreach (var subsubNode in subsubNodes)
                    subFolderNode.Nodes.Add(subsubNode);
                result.Add(subFolderNode);
            }
            return result;
        }

        private void FileManager_Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }
        #endregion

        #region File ListView Event

        void lvFileView_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            lvFileView.ListViewItemSorter = new ListViewItemComparer(e.Column);
            lvFileView.Sort();
        }

        void lvFileView_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if(lvFileView.SelectedItems.Count > 1)
                {
                    var itemCollection = lvFileView.SelectedItems;
                    lvFileView.ContextMenuStrip = cms_FolderRightMenu;
                    foreach (ListViewItem listViewItem in itemCollection)
                    {
                        var isFile = listViewItem.Tag as FileResult;
                        if (null == isFile) continue;
                        lvFileView.ContextMenuStrip = cms_FileRightMenu;
                        break;
                    }
                }
                else
                {
                    var hit = lvFileView.HitTest(e.Location);
                    if (hit.Item != null)
                    {
                        var args = hit.Item.Tag as FileResult;
                        lvFileView.ContextMenuStrip = null == args ? cms_FolderRightMenu : cms_FileRightMenu;
                    }
                }
                lvFileView.ContextMenuStrip.Show();
            }
        }

        void lvFileView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) return;
            //  if(lvFileView.SelectedItems.Count == 1)
            var hit = lvFileView.HitTest(e.Location);
            if (hit.Item != null)
            {
                var args = hit.Item.Tag as FileResult;
                if (null == args)
                {
                    var folderArgs = hit.Item.Tag as NodeArgs;
                    var nodes = tvFileView.Nodes.Find(folderArgs.FolderResult.FileSidk__BackingField, true);
                    if (nodes.Count() == 1)
                    {
                        tvFileView.SelectedNode = nodes[0];
                        tvFileView.SelectedNode.Expand();
                        selectNode = nodes[0];
                        tvFileView.Select();
                        tvFileView.Focus();
                        tvFileView.Update();
                    }
                }
                else
                {
                    var fileArgs = hit.Item.Tag as FileResult;
                    var autoSavePath = Path.GetTempPath();
                    var hasDownload =
                        _downloadingFileProgresses.FirstOrDefault(x => x.FileGuid.Equals(fileArgs.FileSidk__BackingField));
                    if(null != hasDownload)
                    {
                        XtraMessageBox.Show("当前文件正在下载\r\n" + fileArgs.FileNamek__BackingField, "下载提示",
                                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        var downloadFileCollection = new List<FileDoanloadingTemp>
                                                     {
                                                         new FileDoanloadingTemp
                                                             {
                                                                 DownloadLocalPath = autoSavePath,
                                                                 FileSid = fileArgs.FileSidk__BackingField,
                                                                 FolderId = fileArgs.ParentIdk__BackingField,
                                                                 IsOpen = true
                                                             }
                                                     };
                        AddDownloadingProgress(downloadFileCollection);
                    }
                }
            }
        }

        private void pbBigIcon_Click(object sender, EventArgs e)
        {
            lvFileView.View = View.LargeIcon;
        }

        private void pbSmallIcon_Click(object sender, EventArgs e)
        {
            lvFileView.View = View.List;
        }

        private void pbListIcon_Click(object sender, EventArgs e)
        {
            lvFileView.View = View.Details;
        }

        private void pictureBox14_Click(object sender, EventArgs e)
        {
            if (null != tvFileView.SelectedNode.Parent)
            {
                tvFileView.SelectedNode = tvFileView.SelectedNode.Parent;
                tvFileView.Select();
                tvFileView.Focus();
                tvFileView.Update();
            }
                
        }

        #endregion

        #region Department TreeView Event

        void tvFileView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tvFileView.Invalidate(tvFileView.ClientRectangle);
            tvFileView.Update();
        }

        void tvFileView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (null != selectNode)
                selectNode.BackColor = Color.Transparent;
            selectNode = e.Node;
          //  selectNode.BackColor = Color.Blue;
            var tagObj = selectNode.Tag as NodeArgs;
            if(null == tagObj)
            {
                var companyObj = selectNode.Tag as CompanyResult;
                if (companyObj != null && companyObj.Idk__BackingField.Equals(userSession.CompanyIdk__BackingField))
                    tagObj = new NodeArgs
                                 {
                                     FolderResult = new FolderResult
                                                        {
                                                            OwnerIdk__BackingField = companyObj.Idk__BackingField,
                                                            CreateIdk__BackingField = companyObj.Idk__BackingField
                                                        }
                                 };
            }
            SetPbImage(tagObj);
            lvFileView.Items.Clear();
            if (null == tagObj) return;
            var fileQueryArgs = new FileQueryArgs
            {
                FolderIdk__BackingField = tagObj.FolderResult.FileSidk__BackingField,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            if (tagObj.FolderResult.CreateIdk__BackingField.Equals(userSession.UserIdk__BackingField) || tagObj.FolderResult.OwnerIdk__BackingField.Equals(userSession.CompanyIdk__BackingField))
                fileQueryArgs.IsJustMek__BackingField = false;
            else
            {
                if (null == tagObj.FolderRoleResult) return;
                var checkPermission = tagObj.FolderRoleResult.IsCreatek__BackingField | tagObj.FolderRoleResult.IsDeletek__BackingField
                      | tagObj.FolderRoleResult.IsUpdatek__BackingField | tagObj.FolderRoleResult.IsReadk__BackingField;
                if (checkPermission)
                    fileQueryArgs.IsJustMek__BackingField = false;
                else
                    return;
                fileQueryArgs.IsJustMek__BackingField = tagObj.FolderRoleResult.IsJustMek__BackingField;
            }
            var sizeObject =
                departmentSizeResultCollection.DepartmentSizeResultsk__BackingField.FirstOrDefault(
                    x => x.DepartmentSidk__BackingField.Equals(tagObj.FolderResult.OwnerIdk__BackingField));
            if (null != sizeObject)
            {
                var currentSize  = sizeObject.DepartmentSizeMBk__BackingField/1024;
                Lb_DepartmentSize.Text = string.Format("0MB/{0}MB", currentSize);
                pgbRoom.Properties.Maximum = currentSize;
                pgbRoom.Position = 0;
                CurrentDepartmentSize = currentSize;
                CurrentDepartmentUseSize = 0;
            }

            var searchFolderFileBackgroundWorker = new BackgroundWorker();
            searchFolderFileBackgroundWorker.DoWork += searchFolderFileBackgroundWorker_DoWork;
            searchFolderFileBackgroundWorker.RunWorkerCompleted += searchFolderFileBackgroundWorker_RunWorkerCompleted;
            searchFolderFileBackgroundWorker.RunWorkerAsync(fileQueryArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.GetFolderFileCollectionLoadingStr);
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
                loadingWaitForm.ShowDialog();
            }
        }

        private static List<string> SelectFileCollection = new List<string>();
        void searchFolderFileBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (SelectFileCollection.Count <= 0) return;
            Pg_FileManager.Select();
            lvFileView.Focus();
            foreach (var searchFile in SelectFileCollection.Select(fileSid => lvFileView.Items.Find(fileSid, false)).Where(searchFile => searchFile.Length > 0))
            {
                searchFile[0].Selected = true;
                searchFile[0].Focused = true;
            }
            lvFileView.HideSelection = false;
            lvFileView.Select();
            SelectFileCollection.Clear();
        }

        void searchFolderFileBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var fileSearchArgs = e.Argument as FileQueryArgs;
                if (null == fileSearchArgs) return;
                var result = fileService.GetFolderFileCollection(fileSearchArgs);
                var useSize = fileService.GetDepartmentSize(fileSearchArgs.FolderIdk__BackingField);
                Lb_DepartmentSize.Invoke((EventHandler) delegate
                                                            {
                                                                var useStr = string.Format("{0}MB", useSize);
                                                                var newStr = Lb_DepartmentSize.Text.Substring(
                                                                    Lb_DepartmentSize.Text.LastIndexOf("/",
                                                                                                       StringComparison.
                                                                                                           CurrentCultureIgnoreCase));
                                                                Lb_DepartmentSize.Text = useStr + newStr;
                                                                pgbRoom.Position = useSize;
                                                                CurrentDepartmentUseSize = useSize;
                                                            });
                if(null != result)
                {
                    var fileListCollection = new List<ListViewItem>();
                    foreach (var file in result.FileCollectionk__BackingField)
                    {
                        var lvItem = new ListViewItem
                        {
                            Text = file.FileNamek__BackingField,
                            ImageKey = ReturnImageKey(file.FileNamek__BackingField),
                            Tag = file,
                            Name = file.FileSidk__BackingField,
                            ToolTipText = file.FileNamek__BackingField
                        };
                        var lvSubItem0 = new ListViewItem.ListViewSubItem { Text = file.CreateTimek__BackingField.ToShortDateString() };
                        var lvSubItem1 = new ListViewItem.ListViewSubItem { Text = file.CreateNamek__BackingField };
                        var lvSubItem2 = new ListViewItem.ListViewSubItem { Text = file.UpdateTimek__BackingField.ToShortDateString() };
                        var lvSubItem3 = new ListViewItem.ListViewSubItem { Text = file.UpdateNamek__BackingField };
                        var lvSubItem4 = new ListViewItem.ListViewSubItem { Text = file.FileSizek__BackingField + "kb" };
                        var lvSubItem5 = new ListViewItem.ListViewSubItem { Text = "文件" };
                        lvItem.SubItems.Add(lvSubItem0);
                        lvItem.SubItems.Add(lvSubItem1);
                        lvItem.SubItems.Add(lvSubItem2);
                        lvItem.SubItems.Add(lvSubItem3);
                        lvItem.SubItems.Add(lvSubItem4);
                        lvItem.SubItems.Add(lvSubItem5);
                        fileListCollection.Add(lvItem);
                    }
                    TreeNode node = null;
                    tvFileView.Invoke((EventHandler) delegate
                                                         {
                                                             node = tvFileView.SelectedNode;
                                                             var childNodes = node.Nodes;
                                                             foreach (TreeNode childNode in childNodes)
                                                             {
                                                                 var nodeArgs = childNode.Tag as NodeArgs;
                                                                 if (null == nodeArgs) continue;
                                                                 var lvItem = new ListViewItem
                                                                 {
                                                                     Text = nodeArgs.FolderResult.FileNamek__BackingField,
                                                                     ImageKey = GlobalString.System_Image_String.FolderPngImageKey,
                                                                     Tag = nodeArgs,
                                                                     Name = nodeArgs.FolderResult.FileSidk__BackingField,
                                                                     ToolTipText = nodeArgs.FolderResult.FileNamek__BackingField
                                                                 };
                                                                 var lvSubItem0 = new ListViewItem.ListViewSubItem { Text = string.IsNullOrEmpty(nodeArgs.FolderResult.CreateTimek__BackingField) ? "" : DateTime.Parse(nodeArgs.FolderResult.CreateTimek__BackingField).ToShortDateString() };
                                                                 var lvSubItem1 = new ListViewItem.ListViewSubItem { Text = nodeArgs.FolderResult.CreateNamek__BackingField };
                                                                 var lvSubItem2 = new ListViewItem.ListViewSubItem { Text = string.IsNullOrEmpty(nodeArgs.FolderResult.UpdateTimek__BackingField) ? "" : DateTime.Parse(nodeArgs.FolderResult.UpdateTimek__BackingField).ToShortDateString() };
                                                                 var lvSubItem3 = new ListViewItem.ListViewSubItem { Text = nodeArgs.FolderResult.UpdateNamek__BackingField };
                                                                 var lvSubItem4 = new ListViewItem.ListViewSubItem { Text = "" };
                                                                 var lvSubItem5 = new ListViewItem.ListViewSubItem { Text = "文件夹" };
                                                                 lvItem.SubItems.Add(lvSubItem0);
                                                                 lvItem.SubItems.Add(lvSubItem1);
                                                                 lvItem.SubItems.Add(lvSubItem2);
                                                                 lvItem.SubItems.Add(lvSubItem3);
                                                                 lvItem.SubItems.Add(lvSubItem4);
                                                                 lvItem.SubItems.Add(lvSubItem5);
                                                                 fileListCollection.Add(lvItem);
                                                                 tvFileView.Update();
                                                                 //tvFileView.Invalidate(tvFileView.ClientRectangle);
                                                             }
                                                             if (fileListCollection.Count > 0)
                                                             {
                                                                 lvFileView.Invoke((EventHandler)delegate
                                                                 {
                                                                     lvFileView.Items.AddRange(fileListCollection.ToArray());
                                                                 });
                                                             }
                                                         });
                }
                else
                {
                    XtraMessageBox.Show(GlobalString.System_Exception_String.GetFolderFileCollectionExceptionStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        loadingWaitForm.Invoke((EventHandler)delegate
                        {
                            loadingWaitForm.Close();
                        });
                }
                loadingWaitForm.Invoke((EventHandler) delegate
                                                          {
                                                              loadingWaitForm.Close();
                                                          });
            }
            catch (Exception)
            {
                XtraMessageBox.Show(GlobalString.System_Exception_String.GetFolderFileCollectionExceptionStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    loadingWaitForm.Invoke((EventHandler) delegate
                                                              {
                                                                  loadingWaitForm.Close();
                                                              });
            }
        }

        void tvFileView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right) tvFileView.SelectedNode = e.Node;
        }

        private string ReturnImageKey(string fileName)
        {
            var result = string.Empty;
            var fileExtension = Path.GetExtension(fileName).ToLower();
            switch (fileExtension)
            {
                case ".docx":
                case ".doc":
                    result = GlobalString.System_Image_String.WordImageKey;
                    break;
                case ".txt":
                    result = GlobalString.System_Image_String.TxtImageKey;
                    break;
                case ".xlsx":
                case ".xls":
                    result = GlobalString.System_Image_String.ExcelImageKey;
                    break;
                case ".pptx":
                case ".ppt":
                    result = GlobalString.System_Image_String.PptImageKey;
                    break;
                case ".accdb":
                    result = GlobalString.System_Image_String.AccessImageKey;
                    break;
                case ".zip":
                    result = GlobalString.System_Image_String.ZipImageKey;
                    break;
                case ".rar":
                    result = GlobalString.System_Image_String.RarImageKey;
                    break;
                case ".pdf":
                    result = GlobalString.System_Image_String.PdfImageKey;
                    break;
                case ".jpg":
                case ".jpeg":
                    result = GlobalString.System_Image_String.JpgImageKey;
                    break;
                case ".png":
                    result = GlobalString.System_Image_String.PngImageKey;
                    break;
                case ".gif":
                    result = GlobalString.System_Image_String.GifImageKey;
                    break;
                case ".bmp":
                    result = GlobalString.System_Image_String.BmpImageKey;
                    break;
                case ".exe":
                    result = GlobalString.System_Image_String.ExeImageKey;
                    break;
                case ".htm":
                case ".html":
                    result = GlobalString.System_Image_String.HtmlImageKey;
                    break;
                case ".xml":
                    result = GlobalString.System_Image_String.HtmlImageKey;
                    break;
                case ".mp3":
                    result = GlobalString.System_Image_String.Mp3ImageKey;
                    break;
                case ".wav":
                    result = GlobalString.System_Image_String.WmaImageKey;
                    break;
                case ".avi":
                    result = GlobalString.System_Image_String.AviImageKey;
                    break;
                case ".bat":
                    result = GlobalString.System_Image_String.BatImageKey;
                    break;
                default:
                    result = GlobalString.System_Image_String.HtmlImageKey;
                    break;
            }
            return result;
        }

        public void UpdateListView(string folderId)
        {
            NodeArgs nodeTag = null;
            if(null != tvFileView.SelectedNode)
                    nodeTag = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null!= nodeTag&& nodeTag.FolderResult.FileSidk__BackingField.Equals(folderId))
                tvFileView_AfterSelect(tvFileView, new TreeViewEventArgs(tvFileView.SelectedNode));
            else
            {
                var node = tvFileView.Nodes.Find(folderId, true);
                if (node.Length > 0)
                {
                    node[0].ExpandAll();
                    tvFileView.SelectedNode = node[0];
                }
            }
        }

        private void SetPbImage(NodeArgs tagObj)
        {
            foreach (ToolStripItem item in cms_MyCompanyRootRole.Items)
                item.Enabled = true;
            foreach (ToolStripItem item in cms_FolderRightMenu.Items)
                item.Enabled = true;
            foreach (ToolStripItem item in cms_FileRightMenu.Items)
                item.Enabled = true;
            if (null == tagObj)
            {

                pbSubmitFalse.Image = Resources.baosong_disable;
                pbSubmitFalse.Cursor = Cursors.No;
                pbEditTrue.Image = Resources.edit_disable;
                pbEditTrue.Cursor = Cursors.No;
                pbDownloadFalse.Image = Resources.download_disable;
                pbDownloadFalse.Cursor = Cursors.No;
                pbDeleteFalse.Image = Resources.delete_disable;
                pbDeleteFalse.Cursor = Cursors.No;
                pbCreateTrue.Image = Resources.create_disable;
                pbCreateTrue.Cursor = Cursors.No;
            }
            else
            {
                if (tagObj.FolderResult.CreateIdk__BackingField.Equals(userSession.UserIdk__BackingField)
                    || tagObj.FolderResult.OwnerIdk__BackingField.Equals(userSession.CompanyIdk__BackingField))
                {
                    if (tagObj.FolderRoleResult == null)
                        tagObj.FolderRoleResult = new FolderRoleResult();
                    tagObj.FolderRoleResult.IsCreatek__BackingField = true;
                    tagObj.FolderRoleResult.IsDeletek__BackingField = true;
                    tagObj.FolderRoleResult.IsJustMek__BackingField = true;
                    tagObj.FolderRoleResult.IsReadk__BackingField = true;
                    tagObj.FolderRoleResult.IsUpdatek__BackingField = true;
                }
                else
                {
                    if (tagObj.FolderRoleResult == null)
                        tagObj.FolderRoleResult = new FolderRoleResult();
                    tagObj.FolderRoleResult.IsCreatek__BackingField = false;
                    tagObj.FolderRoleResult.IsDeletek__BackingField = false;
                    tagObj.FolderRoleResult.IsJustMek__BackingField = false;
                    tagObj.FolderRoleResult.IsReadk__BackingField = false;
                    tagObj.FolderRoleResult.IsUpdatek__BackingField = false;
                }
                pbSubmitFalse.Image = tagObj.FolderRoleResult.IsJustMek__BackingField
                                          ? Resources.permission_baosong
                                          : Resources.baosong_disable;
                pbSubmitFalse.Cursor = tagObj.FolderRoleResult.IsJustMek__BackingField
                                           ? Cursors.Arrow
                                           : Cursors.No;
                pbEditTrue.Image = tagObj.FolderRoleResult.IsUpdatek__BackingField
                                       ? Resources.permission_edit
                                       : Resources.edit_disable;
                pbEditTrue.Cursor = tagObj.FolderRoleResult.IsUpdatek__BackingField
                                        ? Cursors.Arrow
                                        : Cursors.No;
                pbDownloadFalse.Image = tagObj.FolderRoleResult.IsReadk__BackingField
                                            ? Resources.permission_download
                                            : Resources.download_disable;
                pbDownloadFalse.Cursor = tagObj.FolderRoleResult.IsReadk__BackingField
                                             ? Cursors.Arrow
                                             : Cursors.No;
                pbDeleteFalse.Image = tagObj.FolderRoleResult.IsDeletek__BackingField
                                          ? Resources.permission_delete
                                          : Resources.delete_disable;
                pbDeleteFalse.Cursor = tagObj.FolderRoleResult.IsDeletek__BackingField
                                           ? Cursors.Arrow
                                           : Cursors.No;
                pbCreateTrue.Image = tagObj.FolderRoleResult.IsCreatek__BackingField
                                         ? Resources.permission_create
                                         : Resources.create_disable;
                pbCreateTrue.Cursor = tagObj.FolderRoleResult.IsCreatek__BackingField
                                          ? Cursors.Arrow
                                          : Cursors.No;
            }
            cms_FileRightMenu.Items["tsmi_RenameFile"].Enabled = pbEditTrue.Cursor == Cursors.Arrow;
            cms_FolderRightMenu.Items["tsmi_RenameFolder"].Enabled = pbEditTrue.Cursor == Cursors.Arrow;
            cms_FileRightMenu.Items["tmsi_DownloadFile"].Enabled = pbDownloadFalse.Cursor == Cursors.Arrow;
            cms_FileRightMenu.Items["tsmi_DeleteFile"].Enabled = pbDeleteFalse.Cursor == Cursors.Arrow;
            cms_FolderRightMenu.Items["tsmi_DeleteFolder"].Enabled = pbDeleteFalse.Cursor == Cursors.Arrow;
            //
        }
        #endregion

        #region Update Folder Name
        public void UpdateFolderName(string folderSid, string folderNewName)
        {
            var nodeCollection = tvFileView.Nodes.Find(folderSid, true);
            if (nodeCollection.Length == 1)
                nodeCollection[0].Text = folderNewName;
            var itemCollection = lvFileView.Items.Find(folderSid, false);
            if (itemCollection.Length == 1)
                itemCollection[0].Text = folderNewName;
        }
        #endregion

        #region Navigation ToolBar Event
        private void ToolBar_System_SelectedItemChanged(object sender, EventArgs e)
        {
            
        }

        private void ToolBar_System_SelectedIndexChanged(object sender, EventArgs e)
        {
            var toolBarSelectIndex = (sender as Paway.Windows.Forms.ToolBar).SelectedIndex;
            var enumPage = (PageEnum) toolBarSelectIndex;
            switch (enumPage)
            {
                    case PageEnum.FileSearchPage:
                    Xtab_ManagerPage.SelectedTabPage = Pg_FileSearch;
                    break;
                    case PageEnum.FileManagerPage:
                    Xtab_ManagerPage.SelectedTabPage = Pg_FileManager;
                    break;
                    case PageEnum.FileUploadPage:
                    Xtab_ManagerPage.SelectedTabPage = Pg_Upload;
                    break;
                    case PageEnum.FileSystemSettingPage:
                    Xtab_ManagerPage.SelectedTabPage = Pg_SystemSetting;
                    break;
                    case PageEnum.FileDownloadPage:
                    Xtab_ManagerPage.SelectedTabPage = Pg_Download;
                    break;
            }
        }
        #endregion

        #region Button Upload File Event
        private void btnUploadFile_Click(object sender, EventArgs e)
        {
            if (pbSubmitFalse.Cursor == Cursors.No && pbEditTrue.Cursor == Cursors.No && pbDeleteFalse.Cursor == Cursors.No
              && pbCreateTrue.Cursor == Cursors.No)
                return;
            if(null == tvFileView.SelectedNode) return;
            var nodeArgs = tvFileView.SelectedNode.Tag as NodeArgs;
            if(null == nodeArgs)
            {
                XtraMessageBox.Show("请选择文件夹!", GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                return;
            }
            var dlg = new OpenFileDialog { Multiselect = true, RestoreDirectory = true }; //创建一个OpenFileDialog  
            if (dlg.ShowDialog() != DialogResult.OK) return;
            if (dlg.FileNames == null || !dlg.FileNames.Any()) return;
            var message = string.Format(GlobalString.System_Config_String.UploadFileMessageBox,
                                        dlg.FileNames.Count());
            XtraMessageBox.AllowCustomLookAndFeel = true;
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            //var willDelete = new List<string>();
            var filePathCollection = dlg.FileNames.ToList();
            var uploadingCollection = new List<UploadFileProgress>();
            long userDiskSize;
            var userDiskFlag = long.TryParse(userSession.DiskLargek__BackingField, out userDiskSize);
            if (!userDiskFlag)
                userDiskSize = 0;
            else
                userDiskSize = userDiskSize*1024*1024;
            var fileCountSize = filePathCollection.Select(uploadFileProgress => new FileInfo(uploadFileProgress)).Select(fileInfo => Math.Round((fileInfo.Length/1024.0)/1024, 2)).Sum();
            if (CurrentDepartmentUseSize + fileCountSize>CurrentDepartmentSize)
            {
                XtraMessageBox.Show("已经超出当前部门上传总大小，请选择压缩文件或者联系管理员!", GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK,
                                   MessageBoxIcon.Information);
                return;
            }
            foreach (var temp in filePathCollection)
            {
                var hasFile = false;
                var fileInfo = new FileInfo(temp);
                foreach (var item in lvFileView.Items.Cast<ListViewItem>().Where(item => item.Text.Equals(fileInfo.Name)))
                    hasFile = true;
                if (hasFile)
                {
                    message = string.Format("服务器已包含 {0} 文件，是否覆盖?", fileInfo.Name);
                    if (XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                        continue;
                }
                if (fileInfo.Length > userDiskSize)
               {
                   message = string.Format("文件 {0} 已超过用户最大上传限制!", fileInfo.Name);
                   XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK,
                                       MessageBoxIcon.Error);
                       continue;
               }
                var uplaodingHas =
                    UploadingFileCollection.FirstOrDefault(
                        x => x.FileName.Equals(fileInfo.Name) && x.FileLocalPath.Equals(fileInfo.FullName));
                if(null != uplaodingHas)
                {
                    message = string.Format("文件 {0} 正在上传，请稍后再操作!", fileInfo.Name);
                    XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                        continue;
                }
                var displaySize = Math.Round((fileInfo.Length / 1024.0)/1024, 2);
                uploadingCollection.Add(new UploadFileProgress
                {
                    FileGuid = Guid.NewGuid().ToString(),
                    BeginTime = DateTime.Now,
                    FileLocalPath = fileInfo.FullName,
                    FileName = fileInfo.Name,
                    DisplaySize = displaySize,
                    FileSize = fileInfo.Length,
                    CurrentState = "正在创建连接",
                    UploadingState = UploadingStateEnum.CreateConnectToServer,
                    FolderId = nodeArgs.FolderResult.FileSidk__BackingField
                });
            }
            AddUploadFile(uploadingCollection);
        }
        #endregion

        #region Root company and sub other company root role context menu event
        /// <summary>
        /// Root company and other company root haven't context menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cms_NoRole_Opening(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
        #endregion

        #region Other Company Folder Has Role Context Menu Event
        private void tsmi_OpenFolder_Click(object sender, EventArgs e)
        {
            var args = lvFileView.SelectedItems[0].Tag as FileResult;
            if (null != args) return;
            var folderArgs = lvFileView.SelectedItems[0].Tag as NodeArgs;
            var nodes = tvFileView.Nodes.Find(folderArgs.FolderResult.FileSidk__BackingField, true);
            if (nodes.Count() == 1)
                tvFileView.SelectedNode = nodes[0];
        }

        private void tsmi_FolderCopyTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as NodeArgs;
            if (null == obj) return;
            var folderCopy = new FileCopyToForm(FolderFileDoEnum.FolderCopy, obj.FolderResult.FileSidk__BackingField);
            folderCopy.ShowDialog();
        }

        private void tsmi_FolderCutTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as NodeArgs;
            if (null == obj) return;
            var folderCopy = new FileCopyToForm(FolderFileDoEnum.FolderCut, obj.FolderResult.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        private void tsmi_RenameFolder_Click(object sender, EventArgs e)
        {
            var currentFolder = tvFileView.SelectedNode.Tag as NodeArgs;
            var fileNameCollection = (from ListViewItem item in lvFileView.Items select item.Text).ToList();
            var currentFileName = lvFileView.SelectedItems[0].Text;
            var fileSid = (lvFileView.SelectedItems[0].Tag as NodeArgs).FolderResult.FileSidk__BackingField;
            fileNameCollection.Remove(currentFileName);
            var reNameFolderForm = new ReNameFolderForm(fileNameCollection, fileSid, currentFileName, this);
            reNameFolderForm.ShowDialog();
        }

        private void tsmi_DeleteFolder_Click(object sender, EventArgs e)
        {
            var delItem = lvFileView.SelectedItems[0].Text;
            var message = string.Format(GlobalString.System_Config_String.DeleteFolderMessageBox, delItem);
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var folderDeleteArgs = new FolderDeleteArgs
            {
                FolderSidk__BackingField =
                    (lvFileView.SelectedItems[0].Tag as NodeArgs).FolderResult.FileSidk__BackingField,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            var backgroundWokerDeleteFolder = new BackgroundWorker();
            backgroundWokerDeleteFolder.DoWork += backgroundWokerDeleteFolder_DoWork;
            backgroundWokerDeleteFolder.RunWorkerCompleted += backgroundWokerDeleteFolder_RunWorkerCompleted;
            backgroundWokerDeleteFolder.RunWorkerAsync(folderDeleteArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.DeleteingFolderStr);
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
                loadingWaitForm.ShowDialog();
                // _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.ShowDialog(); });
            }
        }

        #endregion

        #region My Company Root Folder Context Menu Event
        private void tsmi_MyCompanyRootNewFolder_Click(object sender, EventArgs e)
        {
            var nodeArgs = tvFileView.SelectedNode.Tag as NodeArgs;
            var parentId = string.Empty;
            parentId = null == nodeArgs ? (tvFileView.SelectedNode.Tag as CompanyResult).Idk__BackingField : nodeArgs.FolderResult.FileSidk__BackingField;
            var hasFolderName = (from TreeNode node in tvFileView.SelectedNode.Nodes select node.Text).ToList();
            var newFolder = new AddFileForm(hasFolderName, parentId, this);
            newFolder.ShowDialog();
            InitializeTreeView();
            UpdateListView(parentId);
        }

        private void tsmi_MyCompanyRootLogQuery_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var fileSidCollection = new List<string> { tvFileView.SelectedNode.Name };
            fileSidCollection.AddRange(from TreeNode treeNode in tvFileView.SelectedNode.Nodes select treeNode.Name);
            var fileLogs = new FileLogsForm(fileSidCollection);
            fileLogs.ShowDialog();
        }

        #endregion

        #region Other Company Folder Haven't Role Context Menu Event
        private void tsmi_Log_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var fileSidCollection = new List<string> { tvFileView.SelectedNode.Name };
            fileSidCollection.AddRange(from TreeNode treeNode in tvFileView.SelectedNode.Nodes select treeNode.Name);
            var fileLogs = new FileLogsForm(fileSidCollection);
            fileLogs.ShowDialog();
        }

        private void tsmi_OtherComapnyRoleCopyTo_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null == obj) return;
            if (null == obj.FolderRoleResult && !obj.FolderResult.OwnerIdk__BackingField.Equals(userSession.CompanyIdk__BackingField))
            {
                XtraMessageBox.Show(GlobalString.System_Config_String.FolderHaventRoleStr,
                                    GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
            }
            else
            {
                var rightsManageMent = new RightsManagementForm(obj.FolderResult.FileSidk__BackingField, obj, true);
                rightsManageMent.ShowDialog();
            }
        }
        #endregion

        #region My Company Folder Context Menu Event
        private void tsmi_MyCompanyNewFolder_Click(object sender, EventArgs e)
        {
            var nodeArgs = tvFileView.SelectedNode.Tag as NodeArgs;
            var parentId = string.Empty;
            parentId = null == nodeArgs ? (tvFileView.SelectedNode.Tag as CompanyResult).Idk__BackingField : nodeArgs.FolderResult.FileSidk__BackingField;
            var hasFolderName = (from TreeNode node in tvFileView.SelectedNode.Nodes select node.Text).ToList();
            var af = new AddFileForm(hasFolderName, parentId, this);
            af.ShowDialog();
            InitializeTreeView();
            UpdateListView(parentId);
        }

        private void tsmi_MyCompanyDelFolder_Click(object sender, EventArgs e)
        {
            var delItem = tvFileView.SelectedNode.Text;
            var message = string.Format(GlobalString.System_Config_String.DeleteFolderMessageBox, delItem);
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var folderDeleteArgs = new FolderDeleteArgs
            {
                FolderSidk__BackingField =
                    (tvFileView.SelectedNode.Tag as NodeArgs).FolderResult.FileSidk__BackingField,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            var backgroundWokerDeleteFolder = new BackgroundWorker();
            backgroundWokerDeleteFolder.DoWork += backgroundWokerDeleteFolder_DoWork;
            backgroundWokerDeleteFolder.RunWorkerCompleted += backgroundWokerDeleteFolder_RunWorkerCompleted;
            backgroundWokerDeleteFolder.RunWorkerAsync(folderDeleteArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.DeleteingFolderStr);
                // _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.ShowDialog(); });
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
                loadingWaitForm.ShowDialog();
            }
        }

        void backgroundWokerDeleteFolder_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = fileService.DeleteFolder(e.Argument as FolderDeleteArgs);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(GlobalString.System_Exception_String.DeleteFolderExceptionStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Result = null;
            }
        }

        void backgroundWokerDeleteFolder_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var folderDeleteResult = e.Result as FolderDeleteResult;
            if (null != e.Result)
            {
                if (folderDeleteResult.Resultk__BackingField)
                {
                    var parentId = (lvFileView.SelectedItems[0].Tag as NodeArgs).FolderResult.ParentIdk__BackingField;
                    // XtraMessageBox.Show(GlobalString.System_Config_String.DeleteFolderStr, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    var _userService = new UserService();
                    loadingWaitForm.SetCaption(GlobalString.System_Config_String.DeleteFolderLoadingFolderStr);
                    var folderCollectionResult = _userService.SyncGetFolderService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                    loadingWaitForm.SetCaption(GlobalString.System_Config_String.DeleteFolderLoadingFolderRoleStr);
                    var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                    loadingWaitForm.Close();
                    InitializeTreeView();
                    UpdateListView(parentId);
                }
                else
                {
                    loadingWaitForm.Close();
                    var errorMessage = string.Empty;
                    switch (folderDeleteResult.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.DeleteFileNotFileException:
                            errorMessage = GlobalString.System_Exception_String.NotFindFileExceptionStr;
                            break;
                        case BaseExceptionEnum.DeleteFolderException:
                            errorMessage = GlobalString.System_Exception_String.DeleteFolderExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(errorMessage, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            //  Invoke((EventHandler)delegate
            //   {
            loadingWaitForm.Close();
            //   });
        }

        private void tsmi_MyCompanyFolderRename_Click(object sender, EventArgs e)
        {
            var currentFolder = tvFileView.SelectedNode.Tag as NodeArgs;
            var folderNameColletion = (from TreeNode c in tvFileView.SelectedNode.Parent.Nodes select c.Text).ToList();
            var currentFolderName = tvFileView.SelectedNode.Text;
            folderNameColletion.Remove(currentFolderName);
            var reNameFolderForm = new ReNameFolderForm(folderNameColletion, currentFolder.FolderResult.FileSidk__BackingField, currentFolderName, this);
            reNameFolderForm.ShowDialog();
        }

        private void tsmi_MyCompanyFolderLogQuery_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var fileSidCollection = new List<string> { tvFileView.SelectedNode.Name };
            fileSidCollection.AddRange(from TreeNode treeNode in tvFileView.SelectedNode.Nodes select treeNode.Name);
            var fileLogs = new FileLogsForm(fileSidCollection);
            fileLogs.ShowDialog();
        }

        private void tsmi_MyCompanyFolderCopyTo_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null == obj) return;
            var folderCopy = new FileCopyToForm(FolderFileDoEnum.FolderCopy, obj.FolderResult.FileSidk__BackingField);
            folderCopy.Closed += new EventHandler(folderCopy_Closed);
            folderCopy.ShowDialog();
        }

        void folderCopy_Closed(object sender, EventArgs e)
        {
            var folderCopy = sender as FileCopyTo;
            if (null == folderCopy || folderCopy.CopyToFolderSid.Count <= 0) return;
            switch (folderCopy._folderFileDoEnum)
            {
                case FolderFileDoEnum.FolderCut:
                    FolderCut(folderCopy.CutFolderSid, folderCopy._folderOrfileSid);
                    break;
                case FolderFileDoEnum.FolderCopy:
                    FolderCopy(folderCopy.CopyToFolderSid, folderCopy._folderOrfileSid);
                    break;
                case FolderFileDoEnum.FileCut:
                    FileCut(folderCopy.CutFolderSid, folderCopy._folderOrfileSid);
                    break;
                case FolderFileDoEnum.FileCopy:
                    FileCopy(folderCopy.CopyToFolderSid, folderCopy._folderOrfileSid);
                    break;
            }
        }

        private void FolderCut(string targetFolderSid, string folderSid)
        {
            var folderCutBackgroundWorker = new BackgroundWorker();
            folderCutBackgroundWorker.DoWork += folderCutBackgroundWoker_DoWork;
            var folderCutArgs = new FolderCutToArgs
            {
                FolderSidk__BackingField = folderSid,
                TargetFolderSidk__BackingField = targetFolderSid,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            folderCutBackgroundWorker.RunWorkerAsync(folderCutArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.FolderCutStr);
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
            }
            loadingWaitForm.ShowDialog();
        }

        void folderCutBackgroundWoker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsHandleCreated)
                    CreateHandle();
                Invoke((EventHandler)delegate
                {
                    loadingWaitForm.Close();
                });
                var folderCutArgs = e.Argument as FolderCutToArgs;
                var result = fileService.CutFolderTo(folderCutArgs);
                if (result.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        var _userService = new UserService();
                        loadingWaitForm.SetCaption(GlobalString.System_Config_String.DeleteFolderLoadingFolderStr);
                        var folderCollectionResult = _userService.SyncGetFolderService();
                        CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                        loadingWaitForm.SetCaption(GlobalString.System_Config_String.DeleteFolderLoadingFolderRoleStr);
                        var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                        CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                        loadingWaitForm.Close();
                        InitializeTreeView();
                        UpdateListView(folderCutArgs.FolderSidk__BackingField);
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                        case BaseExceptionEnum.CutFolderException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("folderCutBackgroundWoker_DoWork has problem", ex);
                XtraMessageBox.Show("剪切文件夹失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }

        private void FolderCopy(List<string> targetCollection, string folderSid)
        {
            var folderCopyBackgroundWorker = new BackgroundWorker();
            folderCopyBackgroundWorker.DoWork += folderCopyBackgroundWoker_DoWork;
            var folderCopyArgs = new FolderCopyToArgs
            {
                FolderSidk__BackingField = folderSid,
                TargetFolderSidk__BackingField = targetCollection.ToArray(),
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            folderCopyBackgroundWorker.RunWorkerAsync(folderCopyArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.FolderCopyStr);
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
            }
            loadingWaitForm.ShowDialog();
        }

        void folderCopyBackgroundWoker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsHandleCreated)
                    CreateHandle();
                var folderCopyArgs = e.Argument as FolderCopyToArgs;
                var result = fileService.CopyFolderTo(folderCopyArgs);
                Invoke((EventHandler)delegate
                {
                    loadingWaitForm.Close();
                });
                if (result.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        var _userService = new UserService();
                        loadingWaitForm.SetCaption(GlobalString.System_Config_String.DeleteFolderLoadingFolderStr);
                        var folderCollectionResult = _userService.SyncGetFolderService();
                        CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                        loadingWaitForm.SetCaption(GlobalString.System_Config_String.DeleteFolderLoadingFolderRoleStr);
                        var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                        CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                        loadingWaitForm.Close();
                        InitializeTreeView();
                        UpdateListView(folderCopyArgs.FolderSidk__BackingField);
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                        case BaseExceptionEnum.CopyFolderException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("folderCopyBackgroundWoker_DoWork has problem", ex);
                XtraMessageBox.Show("复制文件夹失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }

        private void FileCopy(List<string> targetCollection, string folderSid)
        {
            var fileCopyBackgroundWorker = new BackgroundWorker();
            fileCopyBackgroundWorker.DoWork += fileCopyBackgroundWorker_DoWork;
            var fileCopyArgs = new FileCopyToArgs
            {
                FileSidk__BackingField = folderSid,
                TargetFolderSidk__BackingField = targetCollection.ToArray(),
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            fileCopyBackgroundWorker.RunWorkerAsync(fileCopyArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.FileCopyStr);
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
            }
            loadingWaitForm.ShowDialog();
        }

        void fileCopyBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsHandleCreated)
                    CreateHandle();
                Invoke((EventHandler)delegate
                {
                    loadingWaitForm.Close();
                });
                var fileCopyArgs = e.Argument as FileCopyToArgs;
                var result = fileService.CopyFileTo(fileCopyArgs);
                if (result.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        UpdateListView(tvFileView.SelectedNode.Name);
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                        case BaseExceptionEnum.CopyFileException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }

            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("fileCopyBackgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("复制文件失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }

        private void FileCut(string targetFolderSid, string folderSid)
        {
            var fileCutBackgroundWorker = new BackgroundWorker();
            fileCutBackgroundWorker.DoWork += fileCutBackgroundWorker_DoWork;
            var fileCutArgs = new FileCutToArgs
            {
                FileSidk__BackingField = folderSid,
                TargetFolderSidk__BackingField = targetFolderSid,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            fileCutBackgroundWorker.RunWorkerAsync(fileCutArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
            }
            loadingWaitForm.ShowDialog();
        }

        void fileCutBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsHandleCreated)
                    CreateHandle();
                Invoke((EventHandler)delegate
                {
                    loadingWaitForm.Close();
                });
                var fileCutArgs = e.Argument as FileCutToArgs;
                var result = fileService.CutFileTo(fileCutArgs);
                if (result.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        UpdateListView(tvFileView.SelectedNode.Name);
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (result.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFolderExceptionStr;
                            break;
                        case BaseExceptionEnum.CutFileException:
                            message = GlobalString.System_Exception_String.GetFolderRoleExceptionStr;
                            break;
                        case BaseExceptionEnum.FileUploading:
                            message = GlobalString.System_Exception_String.FileUploadingExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("fileCutBackgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("剪切文件失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
        }

        private void tsmi_MyCompanyFolderCutTo_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null == obj) return;
            var folderCopy = new FileCopyToForm(FolderFileDoEnum.FolderCut, obj.FolderResult.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        private void tsmi_MyCompanyFolderRoleManage_Click(object sender, EventArgs e)
        {
            if (null == tvFileView.SelectedNode) return;
            var obj = tvFileView.SelectedNode.Tag as NodeArgs;
            if (null == obj) return;
            var folderSid = (tvFileView.SelectedNode.Tag as NodeArgs).FolderResult.FileSidk__BackingField;
            var rm = new RightsManagementForm(folderSid, null);
            rm.ShowDialog();
        }

        private void cms_FolderRightMenu_Opening(object sender, CancelEventArgs e)
        {
            if (lvFileView.SelectedItems.Count == 0)
            {
                e.Cancel = true;
            }
        }
        #endregion

        #region File Context Menu Event
        private void tsmi_RenameFile_Click(object sender, EventArgs e)
        {
            var currentFolder = tvFileView.SelectedNode.Tag as NodeArgs;
            var fileNameCollection = (from ListViewItem item in lvFileView.Items select item.Text).ToList();
            var currentFileName = lvFileView.SelectedItems[0].Text;
            var fileSid = (lvFileView.SelectedItems[0].Tag as FileResult).FileSidk__BackingField;
            fileNameCollection.Remove(currentFileName);
            var reNameForm = new ReNameFileForm(fileNameCollection, fileSid, currentFileName,
                                            currentFolder.FolderResult.FileSidk__BackingField, this);
            reNameForm.ShowDialog();
        }

        private void tsmi_FileCopyTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as FileResult;
            if (null == obj) return;
            var folderCopy = new FileCopyToForm(FolderFileDoEnum.FileCopy, obj.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        private void tsmi_FileCutTo_Click(object sender, EventArgs e)
        {
            if (lvFileView.SelectedItems.Count <= 0) return;
            var obj = lvFileView.SelectedItems[0].Tag as FileResult;
            if (null == obj) return;
            var folderCopy = new FileCopyToForm(FolderFileDoEnum.FileCut, obj.FileSidk__BackingField);
            folderCopy.Closed += folderCopy_Closed;
            folderCopy.ShowDialog();
        }

        private void tsmi_DeleteFile_Click(object sender, EventArgs e)
        {
            var delItem = lvFileView.SelectedItems[0].Text;
            var message = string.Format(GlobalString.System_Config_String.DeleteFileMessageBox, delItem);
            if (
                XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information) != DialogResult.Yes) return;
            var fileDeleteArgs = new FileDeleteArgs
            {
                FileSidk__BackingField =
                    (lvFileView.SelectedItems[0].Tag as FileResult).FileSidk__BackingField,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            var backgroundWorkerDeleteFile = new BackgroundWorker();
            backgroundWorkerDeleteFile.DoWork += backgroundWorkerDeleteFile_DoWork;
            backgroundWorkerDeleteFile.RunWorkerCompleted += backgroundWorkerDeleteFile_RunWorkerCompleted;
            backgroundWorkerDeleteFile.RunWorkerAsync(fileDeleteArgs);
            lock (_lockObj)
            {
                loadingWaitForm = new LoadingWaitForm();
                loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                loadingWaitForm.SetDescription(GlobalString.System_Config_String.DeleteingFileStr);
                // _waitBeforeLogin.Invoke((EventHandler)delegate { _waitBeforeLogin.ShowDialog(); });
                loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
            }
            loadingWaitForm.ShowDialog();
        }

        void backgroundWorkerDeleteFile_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            loadingWaitForm.Close();
            var fileDeleteResult = e.Result as FileDeleteResult;
            if (null != e.Result)
            {
                if (fileDeleteResult.Resultk__BackingField)
                {
                    XtraMessageBox.Show(GlobalString.System_Config_String.DeleteFileStr, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    var folderResult = (tvFileView.SelectedNode.Tag as NodeArgs).FolderResult;
                    UpdateListView(folderResult.FileSidk__BackingField);
                }
                else
                {
                    var errorMessage = string.Empty;
                    switch (fileDeleteResult.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.DeleteFileNotFileException:
                            errorMessage = GlobalString.System_Exception_String.NotFindFileExceptionStr;
                            break;
                        case BaseExceptionEnum.DeleteFileException:
                            errorMessage = GlobalString.System_Exception_String.DeleteFileExceptionStr;
                            break;
                        case BaseExceptionEnum.FileUploading:
                            errorMessage = GlobalString.System_Exception_String.FileUploadingExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(errorMessage, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        void backgroundWorkerDeleteFile_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = fileService.DeleteFile(e.Argument as FileDeleteArgs);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(GlobalString.System_Exception_String.DeleteFileExceptionStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Result = null;
            }
        }

        private void tmsi_DownloadFile_Click(object sender, EventArgs e)
        {
            var dialog = new FolderBrowserDialog {Description = "请选择文件保存路径"};
            if (dialog.ShowDialog() != DialogResult.OK) return;
            var foldPath = dialog.SelectedPath;
            //MessageBox.Show("已选择文件夹:" + foldPath, "选择文件夹提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            var downloadFileCollection = new List<FileDoanloadingTemp>();
            var hasFileDownloading = new List<string>();
            for (var index = 0; index < lvFileView.SelectedItems.Count; index++)
            {
                var selectedItem = lvFileView.SelectedItems[index];
                var fileObj = selectedItem.Tag as FileResult;
                if (null == fileObj || string.IsNullOrEmpty(fileObj.FileSidk__BackingField)) continue;
                if (null == _downloadingFileProgresses.FirstOrDefault(x => x.FileGuid.Equals(fileObj.FileSidk__BackingField)))
                    downloadFileCollection.Add(new FileDoanloadingTemp
                                                   {
                                                       DownloadLocalPath = foldPath,
                                                       FileSid = fileObj.FileSidk__BackingField,
                                                       FolderId = fileObj.ParentIdk__BackingField
                                                   });
                else
                    hasFileDownloading.Add(fileObj.FileNamek__BackingField);
            }
            if(hasFileDownloading.Count > 0)
            {
                var messageStr = hasFileDownloading.Aggregate("以下文件正在下载，请稍后操作!", (current, temp) => current + ("\r\n" + temp));
                XtraMessageBox.Show(messageStr, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            AddDownloadingProgress(downloadFileCollection);
        }

        private void cms_FileRightMenu_Opening(object sender, CancelEventArgs e)
        {
            if (lvFileView.SelectedItems.Count == 0)
            {
                e.Cancel = true;
            }
        }
        #endregion

        #region Button Search File Event
        private void BtnBeginSearch_Click(object sender, EventArgs e)
        {
            SearchFileMethod();
        }

        private void BtnEndSearch_Click(object sender, EventArgs e)
        {
            if (null != backgroundWorkerSearchFile && backgroundWorkerSearchFile.IsBusy)
                backgroundWorkerSearchFile.CancelAsync();
            if (null != loadingWaitForm && !loadingWaitForm.IsDisposed)
                loadingWaitForm.Close();
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            txtFileName.Text = "";
            txtAuthor.Text = "";
            dtpBeginTime.Text = "";
            dtpEndtiome.Text = "";
            olv_SearchFile.ClearObjects();
            olv_SearchFile.Items.Clear();
        }
        #endregion

        #region Search File Method
        private BackgroundWorker backgroundWorkerSearchFile;
        private void SearchFileMethod()
        {
            if (string.IsNullOrEmpty(txtFileName.Text.Trim()) &&
               string.IsNullOrEmpty(txtAuthor.Text.Trim()) &&
               string.IsNullOrEmpty(dtpBeginTime.Text) &&
               string.IsNullOrEmpty(dtpEndtiome.Text))
            {
                XtraMessageBox.AllowCustomLookAndFeel = false;
                XtraMessageBox.Show("没有包含任何搜索条件!", GlobalString.System_Config_String.MbxInfoStr,
                                          MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                backgroundWorkerSearchFile = new BackgroundWorker();
                backgroundWorkerSearchFile.DoWork += backgroundWorkerSearchFile_DoWork;
                var fileSearchArgs = new FileSearchArgs
                {
                    CompanyIdk__BackingField = userSession.CompanyIdk__BackingField,
                    FileAuthk__BackingField = txtAuthor.Text.Trim(),
                    FileNamek__BackingField = txtFileName.Text.Trim()
                };
                DateTime beginTime;
                var isTime = DateTime.TryParse(dtpBeginTime.Text, out beginTime);
                fileSearchArgs.BeginTimek__BackingField = !isTime ? DateTime.Now : beginTime;
                DateTime endTime;
                isTime = DateTime.TryParse(dtpEndtiome.Text, out endTime);
                fileSearchArgs.EndTimek__BackingField = !isTime ? fileSearchArgs.BeginTimek__BackingField : endTime;
                backgroundWorkerSearchFile.RunWorkerAsync(fileSearchArgs);
                lock (_lockObj)
                {
                    loadingWaitForm = new LoadingWaitForm();
                    loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                    loadingWaitForm.SetDescription(GlobalString.System_Config_String.FileSearchStr);
                }
                loadingWaitForm.Show();
            }
        }
        void backgroundWorkerSearchFile_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var fileSearchArgs = e.Argument as FileSearchArgs;
                var result = fileService.SearchFile(fileSearchArgs);
                Invoke((EventHandler)delegate
                {
                    loadingWaitForm.Close();
                });
                if (result.ResultExceptionk__BackingField == BaseExceptionEnum.SearchFileException)
                {
                    XtraMessageBox.Show("远程服务器异常，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Error);
                    Invoke((EventHandler)delegate
                    {
                        loadingWaitForm.Close();
                    });
                }
                else
                {
                    var tempObjCollection = result.FileCollectionk__BackingField.Select(fileResult => new SearchFileClass
                    {
                        CreateName = fileResult.CreateNamek__BackingField,
                        FileName = fileResult.FileNamek__BackingField,
                        FilePath = fileResult.FilePathk__BackingField,
                        FolderSid = fileResult.IsFilek__BackingField ? fileResult.ParentIdk__BackingField : fileResult.FileSidk__BackingField,
                        IsJustMe = false,
                        IsCreate = true,
                        IsRead = true,
                        IsUpdate = true,
                        IsDelete = true,
                        LastUpdate = fileResult.UpdateNamek__BackingField,
                        UpdateTime = fileResult.UpdateTimek__BackingField.ToString(),
                        FileSid = fileResult.FileSidk__BackingField
                    }).ToList();
                    olv_SearchFile.SetObjects(tempObjCollection);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("backgroundWorkerSearchFile_DoWork has problem", ex);
                XtraMessageBox.Show("搜索文件失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    loadingWaitForm.Close();
                });
            }
        }
        #endregion

        #region ListView File Search Context Menu Event
        private void cms_SearchFile_Opening(object sender, CancelEventArgs e)
        {
            if (null == olv_SearchFile.SelectedObject)
                e.Cancel = true;
        }

        private void tsmi_MoveToFileFolder_Click(object sender, EventArgs e)
        {
            if (olv_SearchFile.SelectedObject == null) return;
            var obj = olv_SearchFile.SelectedObject as SearchFileClass;
            ToolBar_System.SelectedIndex = (int) PageEnum.FileManagerPage;
            Invoke((EventHandler)delegate
            {
                loadingWaitForm.Close();
                SelectFileCollection.Add(obj.FileSid);
                UpdateListView(obj.FolderSid);
            });
        }
        #endregion

        #region Txtbox Search File  File Name And Author Name Event
        private void txtFileName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            SearchFileMethod();
        }

        private void txtAuthor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            SearchFileMethod();
        }
        #endregion

        #region Upload Manager NavbarControl Event
        private void UploadingFile_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            Xt_UploadManager.SelectedTabPage = Xt_Uploading;
        }

        private void UploadLog_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            Xt_UploadManager.SelectedTabPage = Xt_UploadLog;
        }
        #endregion

        #region Download Manager NavbarControl Event
        private void Nbi_Downloading_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            Xtc_Download.SelectedTabPage = Xtp_Downloading;
        }

        private void Nbi_DownloadLog_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            Xtc_Download.SelectedTabPage = Xtp_DownloadLog;
        }
        #endregion

        private void lvFileView_DragEnter(object sender, DragEventArgs e)
        {
            
        }

        private void lvFileView_DragDrop(object sender, DragEventArgs e)
        {
            
        }
    }

    #region Other Class
    public class NodeArgs
    {
        public FolderResult FolderResult { get; set; }
        public FolderRoleResult FolderRoleResult { get; set; }
    }

    class ListViewItemComparer : IComparer
    {
        private int col;
        public ListViewItemComparer()
        {
            col = 0;
        }
        public ListViewItemComparer(int column)
        {
            col = column;
        }
        public int Compare(object x, object y)
        {
            var returnVal = -1;
            returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
            ((ListViewItem)y).SubItems[col].Text);
            return returnVal;
        }
    }

    public class SearchFileClass
    {
        public string FileName { get; set; }
        public string FilePath { get; set; }
        public bool IsJustMe { get; set; }
        public bool IsCreate { get; set; }
        public bool IsRead { get; set; }
        public bool IsUpdate { get; set; }
        public bool IsDelete { get; set; }
        public string LastUpdate { get; set; }
        public string UpdateTime { get; set; }
        public string CreateName { get; set; }
        public string FolderSid { get; set; }
        public string FileSid { get; set; }
    }

    public enum PageEnum
    {
        FileManagerPage =0,
        FileSearchPage = 1,
        FileUploadPage = 2,
        FileDownloadPage = 3,
        FileSystemSettingPage = 4
    }

    public class TestClass
    {
        public string Name { get; set; }
        public int Height { get; set; }
        public bool TellsJokes { get; set; }
    }
   #endregion
}